package cn.com.bluemoon.daps.system.utils;

import cn.com.bluemoon.dataserver.common.dto.JwtDTO;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.com.bluemoon.dataserver.common.constants.ApiAccountLoginConstants.*;

/**
 * @author Lilike on 2021/7/27
 */
public class JwtUtils {

    /**
     * 秘钥
     */
    private static final String SECRET = "B7cd31aD47c3D860fAd5D5f8799C7Cf0";

    public static final String USER_NAME = "userName";
    public static final String ACCOUNT = "account";


    /**
     * 过期时间 默认12小时过期一次
     **/
    private static final long EXPIRATION = 43200L;//单位为秒

    /**
     * 生成用户token,设置token超时时间
     */
    public static JwtDTO createToken(Map<String,Object> accountInfo) {
        JwtDTO jwtDTO = new JwtDTO();
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim(USER_NAME, (String)accountInfo.get(USER_NAME))
                .withClaim(ACCOUNT, (String)accountInfo.get(ACCOUNT))
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        jwtDTO.setXToken(token);
        jwtDTO.setExpireDate(expireDate);
        return jwtDTO;
    }

    /**
     * 校验token并解析token
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            return null;
        }
        return jwt.getClaims();
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("accessKey","4b4e55ba");

        JwtDTO token = JwtUtils.createToken(map);
        System.out.println(token.getXToken());

        Map<String, Claim> stringClaimMap = JwtUtils.verifyToken(token.getXToken());
        System.out.println(stringClaimMap);
    }
}
